<?php

class CalendarController extends Controller
{

	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
				'accessControl', // perform access control for CRUD operations
				'postOnly + delete', // we only allow deletion via POST request
		);
	}

	public function accessRules()	{
		return array(
				array('allow', 'users'=>array('@')),
				array('deny', 'users'=>array('*')),
		);
	}

	public function actionIndex()
	{
		if ( $this->userType == 2 ) {
			$this->render('keeperCalendar');
		}
		elseif ( $this->userType == 3 ) {
			$this->render('teacherCalendar');
		}
		elseif ( $this->userType == 4) {
			$this->render('studentCalendar');
		}
		else {
			$this->render('index');
		}
	}

	public function actionBookedStudents() {
		$reservId =  $_REQUEST['idTeacherReservation'];

		$studentsRows = StudentReservations::model()->with('user')->findAllBySql("SELECT * FROM StudentReservations WHERE teacher_reservations_id = " . $reservId);

		$list = array();

		foreach ( $studentsRows as $studentRow ) {
			$student = new stdClass();
			$student->name = $studentRow->user->first_name . " " . $studentRow->user->second_name;
			$list[] = $student;
		}
		$result = array( "list" => $list);
		echo CJSON::encode($result);
	}

	public function actionEvents() {

		if ( $this->userType == 2 ) {
			$start = $_REQUEST['start'];
			$end = $_REQUEST['end'];
			$reservationsRows = $this->findKeeperReservations($start, $end);
			$events = $this->keeperReservationsToEvents($reservationsRows);
			echo CJSON::encode($events);
		}
		if ( $this->userType == 3 ) {
			$start = $_REQUEST['start'];
			$end = $_REQUEST['end'];

			$teacherReservationsRows = TeacherReservations::model()->with('keeperReservations')->findAllBySql(
					"SELECT * FROM TeacherReservations WHERE start_date >= FROM_UNIXTIME(:start) AND start_date <= FROM_UNIXTIME(:end) AND NOT is_deleted",
					array( "start" => $start, "end" => $end)
			);
			$reservationsRows = $this->findKeeperReservations($start, $end);
			$keeperEvents = $this->keeperReservationsToEvents($reservationsRows);
				
			$events = array_merge($keeperEvents,$this->teacherReservationsToEvents($teacherReservationsRows));

				
				
			echo CJSON::encode($events);
		}
		if ( $this->userType == 4 ) {
			$start = $_REQUEST['start'];
			$end = $_REQUEST['end'];
				
			$studentReservationsRows = TeacherReservations::model()->with('keeperReservations')->findAllBySql(
					"SELECT * FROM TeacherReservations WHERE start_date >= FROM_UNIXTIME(:start) AND start_date <= FROM_UNIXTIME(:end) AND NOT is_deleted",
					array( "start" => $start, "end" => $end)
			);
				
				
			$events = $this->studentReservationsToEvents($studentReservationsRows);
				
			echo CJSON::encode($events);
		}
	}

	public function findKeeperReservations($start, $end) {
		return KeeperReservations::model()->with('station')
		->with('tools')->findAllBySql(
				"SELECT * FROM KeeperReservations WHERE start_date >= FROM_UNIXTIME(:start) AND start_date <= FROM_UNIXTIME(:end) AND NOT is_deleted",
				array( "start" => $start, "end" => $end)
		);
	}

	public function actionDeleteKeeperReservation(){
		date_default_timezone_set('Europe/Paris');
		if ( $this->userType == 2 ) {
			$id=$_REQUEST['id'];
			if ( !isset ($id) ) {
				return;
			}
			//$id = 39;
			$reservation = $this->loadModel($id);
			$reservation->is_deleted = "1";
			$reservation->save();

			$teachersIdsRange = array();
			$studentsIdsRange = array();
			$teachersReservationsData = array();
			$studentsReservationsData = array();

			$teacherReservations = TeacherReservations::model()->with('keeperReservations')->with('user')->findAllBySql("
					SELECT TR.id, U.email, TR.description, TR.start_date, TR.end_date FROM `TeacherReservations` AS TR,
					`Users` AS U WHERE TR.keeper_reservations_id = :keeperId AND TR.user_id = U.id AND TR.is_deleted != 1;",
					array("keeperId" => $id));

			if(sizeof($teacherReservations) > 0)
			{
				$teachersReservationsData = $this->loadReservations($teacherReservations, 2);
				foreach ($teachersReservationsData as $teachersReservationData)
				{
					array_push($teachersIdsRange, $teachersReservationData->id);
				}
				$studentReservations = StudentReservations::model()->with('teacherReservations')->with('user')->findAllBySql("
						SELECT SR.id, U.email, TR.start_date, TR.end_date,
						TR.description FROM StudentReservations AS SR JOIN TeacherReservations AS TR
						ON SR.teacher_reservations_id = TR.id JOIN Users AS U ON U.id = SR.user_id
						WHERE SR.teacher_reservations_id IN " . '(' . implode(', ', $teachersIdsRange) . ')'
						. " AND SR.user_id = U.id");
				if(sizeof($studentReservations) > 0)
				{
					$studentsReservationsData = $this->loadReservations($studentReservations, 1);
					foreach ($studentsReservationsData as $studentsReservationData)
					{
						array_push($studentsIdsRange, $studentsReservationData->id);
					}
					StudentReservations::model()->deleteByPk($studentsIdsRange);
					$this->sendMail($studentsReservationsData, 0);
				}
				//$criteria = new CDbCriteria;
				//$criteria->addInCondition( "SR.teacher_reservations_id" , $teachersIdsRange );
					
				TeacherReservations::model()->updateByPk($teachersIdsRange, array('is_deleted' => '1'));
				$this->sendMail($teachersReservationsData, 0);
					
			}
			$result = array();
			echo CJSON::encode($result);
		}
	}

	public function actionDeleteTeacherReservation() {
		date_default_timezone_set('Europe/Paris');
		if ( $this->userType == 3 ) {
			$id=$_REQUEST['id'];
			if ( !isset ($id) ) {
				return;
			}
			$reservation = TeacherReservations::model()->findByPk($id);
			$reservation->is_deleted = "1";
			$reservation->save();

				
			$result = array();
			echo CJSON::encode($result);
		}
	}

	public function actionDeleteStudentReservation() {
		date_default_timezone_set('Europe/Paris');
		if ( $this->userType == 4 ) {
			$id=$_REQUEST['id'];
			if ( !isset ($id) ) {
				return;
			}
			$user_id = $this->userId;
			$reservation = StudentReservations::model()->find('user_id=:userId AND teacher_reservations_id=:teacherReservationId',
					array('userId'=>$user_id, 'teacherReservationId'=>$id)
			);
			$reservation->delete();
				
			$result = array();
			echo CJSON::encode($result);
		}
	}

	public function actionEditKeeperReservation(){
		date_default_timezone_set('Europe/Paris');
		if ( $this->userType == 2 ) {
			if(isset($_REQUEST['station']))
			{
				$station = $_REQUEST['station'];
			}
			else
				return;
			if ( isset ($_REQUEST['tools']) ) {
				$tools = $_REQUEST['tools'];
			}
			else {
				$tools = null;
			}
			$id=$_REQUEST['id'];
			if ( !isset ($id) ) {
				return;
			}
			$maintanace=0;
			if ( isset ($_REQUEST['maintanace']) ) {
				$maintanace=1;
			}

			$reservation = $this->loadModel($id);
			$this->actionDeleteKeeperReservation();
			$startdate =  date_parse_from_format('j/n/Y H:i', $_REQUEST['reservationdate'] . ' ' . $_REQUEST['starttime']);
			$enddate = date_parse_from_format('j/n/Y H:i', $_REQUEST['reservationdate'] . ' ' . $_REQUEST['endtime']);
			$reservation->station_id = $station;
			$reservation->is_maintained=$maintanace;
			$reservation->start_date = $this->dateToMysqlDate($startdate);
			$reservation->end_date = $this->dateToMysqlDate($enddate);
			$reservation->save();

			KeeperReservationsHasTools::model()->deleteAll("KeeperReservations_id = :id",
			array( "id" => $id));

			if(isset($tools))
				foreach ( $tools as $toolId) {
				$resvhastool = new KeeperReservationsHasTools;
				$resvhastool->KeeperReservations_id = $reservation->id;
				$resvhastool->Tools_id = $toolId;
				$resvhastool->save();
			}

			$teachersReservationsData = array();
			$studentsReservationsData = array();
			$teachersIdsRange = array();
			$studentsIdsRange = array();

			if($maintanace==0){
				$teachersModifiedReservations = TeacherReservations::model()->with('user')->findAllBySql('
					SELECT * FROM (SELECT TR.id, TR.description, U.email, TR.start_date, TR.end_date, TR.is_deleted FROM `TeacherReservations` AS TR,
					`Users` AS U WHERE TR.keeper_reservations_id = :id AND TR.user_id = U.id) as tmp WHERE tmp.start_date NOT BETWEEN
					:start_date AND :end_date AND tmp.is_deleted != 1 OR tmp.end_date NOT BETWEEN :start_date AND :end_date
					AND tmp.is_deleted != 1 ;',
					array('start_date' => $reservation->start_date, 'end_date' => $reservation->end_date, 'id' => $id, 'maintenance' => $maintanace));
			}else{
				$teachersModifiedReservations = TeacherReservations::model()->with('user')->findAllBySql('
					SELECT * FROM (SELECT TR.id, TR.description, U.email, TR.start_date, TR.end_date, TR.is_deleted FROM `TeacherReservations` AS TR,
					`Users` AS U WHERE TR.keeper_reservations_id = :id AND TR.user_id = U.id) as tmp;',
					array( 'id' => $id));
			}

			if(sizeof($teachersModifiedReservations) > 0)
			{
				$teachersReservationsData = $this->loadReservations($teachersModifiedReservations, 2);
				foreach ($teachersReservationsData as $teachersReservationData)
				{
					array_push($teachersIdsRange, $teachersReservationData->id);
				}
				$studentModifiedReservations = StudentReservations::model()->with('teacherReservations')->with('user')->findAllBySql("
						SELECT SR.id, U.email, TR.start_date, TR.end_date,
						TR.description FROM StudentReservations AS SR JOIN TeacherReservations AS TR
						ON SR.teacher_reservations_id = TR.id JOIN Users AS U ON U.id = SR.user_id
						WHERE SR.teacher_reservations_id IN " . '(' . implode(', ', $teachersIdsRange) . ')'
						. " AND SR.user_id = U.id");
				
				if(sizeof($studentModifiedReservations) > 0)
				{
					$studentsReservationsData = $this->loadReservations($studentModifiedReservations, 1);
					foreach ($studentsReservationsData as $studentsReservationData)
					{
						array_push($studentsIdsRange, $studentsReservationData->id);
					}
					StudentReservations::model()->deleteByPk($studentsIdsRange);
					if($maintanace==1)
						$this->sendMail($studentsReservationsData, 2);
					else
						$this->sendMail($studentsReservationsData, 1);
				}
				TeacherReservations::model()->updateByPk($teachersIdsRange, array('is_deleted' => '1'));
				if($maintanace==1)
					$this->sendMail($teachersReservationsData, 2);
				else
					$this->sendMail($teachersReservationsData, 1);
			}
			$result = array();
			echo CJSON::encode($result);
		}
	}

	public function actionEditTeacherReservation(){
		$id = $_REQUEST['id'];
		$reservation = TeacherReservations::model()->findByPk($id);
			
		$reservation->description = $_REQUEST['name'];
		$reservation->limit = $_REQUEST['limit'];
		$reservation->save();
			
		$result = array();
		echo CJSON::encode($result);
	}

	public function actionEditStudentReservation(){

		$id = 0;
		if(isset($_REQUEST['id'])){
			$id=$_REQUEST['id'];
		}
		$user_id = $this->userId;

		$resrv = StudentReservations::model()->with('teacherReservations')->findAllBySql(
				"SELECT * FROM StudentReservations WHERE user_id =:userid AND teacher_reservations_id =:id",
				array("userid" => $user_id, "id" => $id)
		);

		$result = array("reserv" =>$resrv);
		echo CJSON::encode($result);
	}

	public function actionGetKeeperReservation(){
		if ( $this->userType == 2 ) {
			$id=$_REQUEST['id'];
			if ( !isset ($id) ) {
				return;
			}
			$reservation= KeeperReservation::model()->with('station')->with('tools')->findAllBySql(
					"SELECT * FROM KeeperReservations WHERE id= :id AND NOT is_deleted",
					array( "id" => $id)
			);
			$event = $this->keeperReservationToEvent($reservation);
		}
	}

	public function actionAddKeeperReservation() {
		date_default_timezone_set('Europe/Paris');
		if ( $this->userType == 2 ) {
			$station = $_REQUEST['station'];
			if ( isset ($_REQUEST['tools']) ) {
				$tools = $_REQUEST['tools'];
			}
			else {
				$tools = null;
			}
			$startdate =  date_parse_from_format('j/n/Y H:i', $_REQUEST['reservationdate'] . ' ' . $_REQUEST['starttime']);
			$enddate = date_parse_from_format('j/n/Y H:i', $_REQUEST['reservationdate'] . ' ' . $_REQUEST['endtime']);
			$repeatEndDate = date_parse_from_format('j/n/Y', $_REQUEST['repeatEndDate']);
			if (isset ($_REQUEST['eventRepeat']))
			{
				$startDate = new DateTime(str_replace('/', '-', $_REQUEST['reservationdate']. ' ' . $_REQUEST['starttime']));
				$endDate = new DateTime(str_replace('/', '-', $_REQUEST['reservationdate'] . ' ' . $_REQUEST['endtime']));
				$repeatEndDate = new DateTime(str_replace('/', '-', $_REQUEST['repeatEndDate']. ' ' . $_REQUEST['endtime']));
				$repeatType = $_REQUEST['eventRepeat'];
				$startAndEndDates = array();
				if($repeatType == 'Weekly' && isset($_REQUEST['days']))
				{
					$days = $_REQUEST['days'];
					$startAndEndDates = $this->calculateRecuringDates($repeatType, $startDate, $endDate, $repeatEndDate, $days);
					//var_dump($startAndEndDates);
				}
				else if($repeatType == 'Monthly' && isset($_REQUEST['monthday']))
				{
					$monthday = $_REQUEST['monthday'];
					$startAndEndDates = $this->calculateRecuringDates($repeatType, $startDate, $endDate, $repeatEndDate, array($monthday));
					//var_dump($startAndEndDates);
				}
				else if($repeatType == 'Daily')
				{
					$startAndEndDates = $this->calculateRecuringDates($repeatType, $startDate, $endDate, $repeatEndDate, array());
					//var_dump($startAndEndDates);
				}
				else if($repeatType == 'Yearly')
				{
					$startAndEndDates = $this->calculateRecuringDates($repeatType, $startDate, $endDate, $repeatEndDate, array());
					//var_dump($startAndEndDates);
				}



				if($repeatType != 'None')
				{
					$queryForCollisionDates = $this->getCollisionalDates($startAndEndDates, $tools, $station);
					$keeperReservationsDates = Yii::app()->db->createCommand($queryForCollisionDates)->queryAll();
					$countOfCollisionDates = sizeof($keeperReservationsDates);
					if($countOfCollisionDates > 0)
						$intDates = $this->changeDatesToIntArray($keeperReservationsDates);						

					foreach ($startAndEndDates as $startAndEndDate)
					{
						if($countOfCollisionDates > 0)
						{
							if(in_array((int)$startAndEndDate->start_date->format('Ymd'), $intDates))
								continue;
						}	
						$reservation = new KeeperReservations;
						$reservation->user_id = $this->userId;
						$reservation->station_id = $station;
						$reservation->start_date = $startAndEndDate->start_date->format('Y-m-d H:i:s');
						$reservation->end_date = $startAndEndDate->end_date->format('Y-m-d H:i:s');
						$reservation->save();
						if(isset($tools))
							foreach ( $tools as $toolId) {
							$resvhastool = new KeeperReservationsHasTools;
							$resvhastool->KeeperReservations_id = $reservation->id;
							$resvhastool->Tools_id = $toolId;
							$resvhastool->save();
						}
					}
				}
				else
				{
					$reservation = new KeeperReservations;
					$reservation->user_id = $this->userId;
					$reservation->station_id = $station;
					$reservation->start_date = $this->dateToMysqlDate($startdate);
					$reservation->end_date = $this->dateToMysqlDate($enddate);
					$reservation->save();
					if(isset($tools))
						foreach ( $tools as $toolId) {
						$resvhastool = new KeeperReservationsHasTools;
						$resvhastool->KeeperReservations_id = $reservation->id;
						$resvhastool->Tools_id = $toolId;
						$resvhastool->save();
					}
				}

			}
				
			$result = array();
			echo CJSON::encode($result);
		}
	}

	public function actionAddTeacherReservation() {
		if ( $this->userType == 3 ) {
			$startdate =  date_parse_from_format('j/n/Y H:i', $_REQUEST['reservationdate'] . ' ' . $_REQUEST['starttime']);
			$enddate = date_parse_from_format('j/n/Y H:i', $_REQUEST['reservationdate'] . ' ' . $_REQUEST['endtime']);

			$reservation = new TeacherReservations;
			$reservation->user_id = $this->userId;
			$reservation->description = $_REQUEST['name'];
			$reservation->limit = $_REQUEST['limit'];
			$reservation->start_date = $this->dateToMysqlDate($startdate);
			$reservation->end_date = $this->dateToMysqlDate($enddate);
			$reservation->keeper_reservations_id = $_REQUEST['idKeeperReserv'];
				
			$reservation->save();
				
			$result = array();
			echo CJSON::encode($result);
		}
	}

	public function actionAddStudentReservation() {
		if ( $this->userType == 4) {
			$reservation = new StudentReservations;
			$reservation->user_id = $this->userId;
			$reservation->teacher_reservations_id = $_REQUEST['id'];
				
			$reservation->save();
				
			$result = array();
			echo CJSON::encode($result);
		}
	}

	private function dateToMysqlDate($date) {
		return $date['year'] . "-". $date['month'] . "-" .
				$date['day'] . " " . $date['hour'] . ":".$date['minute']. ":" . $date['second'];
	}

	public function actionAvailableStationsAndTools() {
		date_default_timezone_set('Europe/Paris');
		$id = 0;
		if(isset($_REQUEST['id'])){
			$id=$_REQUEST['id'];
		}
		$date_start = $_REQUEST['year'] . "-". $_REQUEST['month'] . "-" . $_REQUEST['day'] . " " .$_REQUEST['hourStart'] . ":" . $_REQUEST['minStart'];
		$date_end = $_REQUEST['year'] . "-". $_REQUEST['month'] . "-" . $_REQUEST['day'] . " " . $_REQUEST['hourStop'] . ":" . $_REQUEST['minStop'];
		$stations = Station::model()->findAllBySql(
				"SELECT * FROM Station WHERE NOT is_deleted AND id NOT IN (
				SELECT s.id FROM `KeeperReservations` r JOIN Station s ON r.station_id = s.id
				WHERE  ((r.start_date >= :start_date AND r.end_date <= :end_date)
				OR r.start_date BETWEEN :start_date AND :end_date OR r.end_date BETWEEN :start_date AND :end_date
				OR :start_date BETWEEN r.start_date AND r.end_date OR :end_date BETWEEN r.start_date AND r.end_date) AND r.id != :id
				AND r.is_deleted != true)",
				array( "end_date" => $date_end, "start_date" => $date_start, "id"=>$id)
		);

		$tools = Tools::model()->findAllBySql(
				"SELECT * FROM Tools WHERE NOT is_deleted AND id NOT IN (
				SELECT Distinct(rt.Tools_id) FROM KeeperReservations r
				JOIN KeeperReservations_has_Tools rt ON r.id = rt.KeeperReservations_id
				WHERE  ((r.start_date >= :start_date AND r.end_date <= :end_date)
				OR r.start_date BETWEEN :start_date AND :end_date OR r.end_date BETWEEN :start_date AND :end_date
				OR :start_date BETWEEN r.start_date AND r.end_date OR :end_date BETWEEN r.start_date AND r.end_date) AND r.id != :id
				AND r.is_deleted != true
		)",
				array( "end_date" => $date_end, "start_date" => $date_start, "id"=>$id)
		);
		$result = array( "stations" => $stations, "tools" => $tools);
		echo CJSON::encode($result);
	}

	public function teacherReserv( $a, $b ) {
		return $a->start_date == $b->start_date ? 0 : ( $a->start_date > $b->start_date ) ? 1 : -1;
	}

	public function actionAvailableStationsForTeacher() {
		date_default_timezone_set('Europe/Paris');
		$date_start = $_REQUEST['year'] . "-". $_REQUEST['month'] . "-" . $_REQUEST['day'] . " " .$_REQUEST['hourStart'] . ":" . $_REQUEST['minStart'];
		$date_end = $_REQUEST['year'] . "-". $_REQUEST['month'] . "-" . $_REQUEST['day'] . " " . $_REQUEST['hourStop'] . ":" . $_REQUEST['minStop'];

		$keeperReservations = KeeperReservations::model()->with('station')->with('teacherReservations')
		->findAllBySql(
				"SELECT * FROM KeeperReservations WHERE start_date >= :start AND start_date <= :end AND NOT is_deleted",
				array( "start" => $date_start, "end" => $date_end)
		);

		$stations = array();

		foreach ( $keeperReservations as $reserv ) {
			$teacherReservations = array();
				
			foreach ( $reserv->teacherReservations as $teacherReserv ) {
				if ( !$teacherReserv->is_deleted ) {
					$teacherReservations[] = $teacherReserv;
				}
			}
				
			if ( count($teacherReservations) < 1 ) {
				$stations[] = $this->createAvailStationForTeacher($reserv, $reserv->start_date, $reserv->end_date);
			}
			else {
				usort( $teacherReservations, 'CalendarController::teacherReserv' );
				$previous_end = $reserv->start_date;
				for ($i = 0; $i < count($teacherReservations); ++$i) {
					$teacherReserv = $teacherReservations[$i];
					if ( $previous_end < $teacherReserv->start_date ) {
						$stations[] = $this->createAvailStationForTeacher($reserv, $previous_end, $teacherReserv->start_date );
					}
					$previous_end = $teacherReserv->end_date;
				}
				 
				if ( $previous_end < $reserv->end_date ) {
					$stations[] = $this->createAvailStationForTeacher($reserv, $previous_end, $reserv->end_date );
				}
			}
		}

		$result = array( "stations" => $stations );

		echo CJSON::encode($result);
	}

	private function buildKeeperReservationLabel($name, $start_date, $end_date ) {
		return  $name . " (" .  $start_date . " - " . $end_date . ")";
	}

	private function createAvailStationForTeacher($reserv, $start_date, $end_date ) {
		$station = new stdClass();
		$station->id = $reserv->id;
		$station->name = $this->buildKeeperReservationLabel($reserv->station->name, $start_date, $end_date);
		$station->start = strtotime($start_date);
		$station->end = strtotime($end_date);
		return $station;
	}

	private function keeperReservationsToEvents($reservationsRows) {
		$events = array();
		foreach ( $reservationsRows as $reservation  ) {
			$events[] = $this->keeperReservationToEvent($reservation);
		}
		return $events;
	}

	private function keeperReservationToEvent($reservationRow) {
		date_default_timezone_set('Europe/Paris');
		$event = new CalendarEvent();
		$event->id=$reservationRow->id;
		$event->title = $reservationRow->station->name;
		$event->start = strtotime($reservationRow->start_date) ;
		$event->end = strtotime($reservationRow->end_date);
		$event->stationId = $reservationRow->station->id;
		$event->tools =$reservationRow->tools;
		$event->is_maintained=$reservationRow->is_maintained;
		$event->ownerType = 2;

		$event->description = "";
		foreach( $reservationRow->tools as $tool) {
			$event->description = $event->description . $tool->name . "; ";
		}
		return $event;
	}

	private function teacherReservationsToEvents($reservationsRows) {
		$events = array();
		foreach ( $reservationsRows as $reservation  ) {
			$events[] = $this->teacherReservationToEvent($reservation);
		}
		return $events;
	}

	private function teacherReservationToEvent(TeacherReservations $reservationRow) {
		date_default_timezone_set('Europe/Paris');
		$event = new CalendarEvent();

		$event->id=$reservationRow->id;
		$event->title = $reservationRow->description;
		$event->start = strtotime($reservationRow->start_date) ;
		$event->end = strtotime($reservationRow->end_date);
		$event->limit = $reservationRow->limit;
		$event->station = $reservationRow->keeperReservations->station->name;

		$event->ownerType = 3;

		return $event;
	}

	private function studentReservationsToEvents($reservationsRows) {
		$events = array();
		foreach ( $reservationsRows as $reservation  ) {
			$events[] = $this->studentReservationToEvent($reservation);
		}
		return $events;
	}

	private function studentReservationToEvent(TeacherReservations $reservationRow) {
		date_default_timezone_set('Europe/Paris');
		$event = new CalendarEvent();
		$user_id = $this->userId;
		$id = $reservationRow->id;

		$event->id=$reservationRow->id;
		$event->title = $reservationRow->description;
		$event->start = strtotime($reservationRow->start_date) ;
		$event->end = strtotime($reservationRow->end_date);
		$event->limit = $reservationRow->limit;
		$event->station = $reservationRow->keeperReservations->station->name;

		$stationsFree = StudentReservations::model()->findAllBySql(
				"SELECT * FROM StudentReservations WHERE teacher_reservations_id = :id",
				array("id" => $id));

		$isReservation = StudentReservations::model()->findAllBySql(
				"SELECT * FROM StudentReservations WHERE teacher_reservations_id = :id AND user_id = :user_id",
				array("id" => $id, "user_id" => $user_id));

		$event->zajete = sizeof($stationsFree);
		$event->reserved = sizeof($isReservation);

		$event->ownerType = 4;

		return $event;
	}

	public function loadModel($id)
	{
		$model=KeeperReservations::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}


	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
	// return the filter configuration for this controller, e.g.:
	return array(
			'inlineFilterName',
			array(
					'class'=>'path.to.FilterClass',
					'propertyName'=>'propertyValue',
			),
	);
	}

	public function actions()
	{

	// return external action classes, e.g.:
	return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
					'class'=>'path.to.AnotherActionClass',
					'propertyName'=>'propertyValue',
			),
	);
	}
	*/
	public function actionCount()
	{
		$connection = Yii::app()->db;

		$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
		$date_start = $date . " " . "00:00:00";
		$date_end = $date . " " . "23:59:59";
			
		$command=$connection->createCommand(
				"SELECT COUNT(*) FROM Reservations
				WHERE start_date >= '" . $date_start . "'
				AND end_date <= '" . $date_end . "' ");

		$dataReader=$command->queryScalar();

		echo CJSON::encode(array('value'=>$dataReader, 'key'=>$date));
	}

	public function sendMail(array $reservations, $ifDeleted)
	{
		if(sizeof($reservations) > 0)
		{
			foreach ($reservations as $reservation)
			{
				//ęąńóćźżł
				switch($ifDeleted){
				case 0:
				
					$title = 'Usunięcie terminu zajęć!';
					$message = 'Zajęcia <b>' . $reservation->description
					. '</b> odbywające się w terminie <b>' . $reservation->start_date
					. '</b> do <b>' . $reservation->end_date
					. '</b> zostały zlikwidowane!';
				
				break;
				case 1:
				
					$title = 'Zmiana w zajęciach!';
					$message = 'Zajęcia w laboratorium laparoskopii, na ktore jestes zapisany, zostały zedytowane, ich aktualne dane to: ' .
							'Opis: <b>' . $reservation->description
							. '</b>Termin zajęc: <b>' . $reservation->start_date
							. '</b> do <b>' . $reservation->end_date
							. '</b>.';
				
				break;
				case 2:
					$title = 'Stanowisko w konserwacji!';
					$message = 'Zajęcia <b>' . $reservation->description
					. '</b> odbywające się w terminie <b>' . $reservation->start_date
					. '</b> do <b>' . $reservation->end_date
					. '</b> zostały odwołane z powodu konserwacji!';
				break;
				}
				Yii::app()->mailer->IsHTML(true);
				Yii::app()->mailer->AddAddress($reservation->email);
				Yii::app()->mailer->Subject = $title;
				Yii::app()->mailer->Body = $this->renderPartial('email', array('message' => $message, 'title' => $title), true);//$message;
				Yii::app()->mailer->Send();
			}
		}
	}
	

	private function loadReservations(array $reservations, $option)
	{
		if(sizeof($reservations) > 0)
		{
			if($option == 2) // teacher
			{
				$teachersReservationsData = array();
				foreach ($reservations as $reservation)
				{
					$teacherReservationData = new stdClass();
					$teacherReservationData->id = $reservation->id;
					$teacherReservationData->email = $reservation->user->email;
					$teacherReservationData->description = $reservation->description;
					$teacherReservationData->start_date = $reservation->start_date;
					$teacherReservationData->end_date = $reservation->end_date;
					$teachersReservationsData[] = $teacherReservationData;
				}
				return $teachersReservationsData;
			}
			else if($option == 1) // student
			{
				$studentsReservationsData = array();
				foreach ($reservations as $reservation)
				{
					$studentReservationsData = new stdClass();
					$studentReservationsData->id = $reservation->id;
					$studentReservationsData->email = $reservation->user->email;
					$studentReservationsData->description = $reservation->teacherReservations->description;
					$studentReservationsData->start_date = $reservation->teacherReservations->start_date;
					$studentReservationsData->end_date = $reservation->teacherReservations->end_date;
					$studentsReservationsData[] = $studentReservationsData;
				}
				return $studentsReservationsData;
			}
			else
				return null;
		}
		else
			return null;
	}

	private function getCollisionalDates(array $reservations, $tools_ids, $station_id)
	{
		/*$command = Yii::app()->db->createCommand()->selectDistinct('KR.start_date, KR.end_date')->from('KeeperReservations KR')
		 ->join('KeepereReservations_has_Tools KRhT','KRhT.KeeperReservations_id=KR.id')
		->join('Tools T', 'T.id=KRhT.tools_id')
		->where('KR.start_date >= :start_date AND KR.end_date <= :end_date AND KR.station_id = :station_id
				AND KR.is_deleted != 1 OR KRhT.Tools_id IN :tools_ids AND KR.start_date >= :start_date
				AND KR.end_date <= :end_date AND T.is_deleted != 1',
				array('start_date' => $start_date, 'end_date' => $end_date, 'station_id' => $station_id,
						'tools_ids' => $tools_ids));*/
		$station_id = $station_id;
		$length = sizeof($reservations);
		if($tools_ids != null)
		{
			$baseQuery = "SELECT DISTINCT tmp.start_date, tmp.end_date FROM (SELECT DISTINCT KRhT.Tools_id, KR.is_deleted, KR.station_id,
					KR.start_date, KR.end_date FROM KeeperReservations as KR LEFT JOIN KeeperReservations_has_Tools
					as KRhT ON KR.id = KRhT.KeeperReservations_id LEFT JOIN Tools as T ON KRhT.tools_id = T.id WHERE ";
			$tools_ids_imploded = implode(',', $tools_ids);
			for ($i = 0; $i < $length; $i++)
			{
				$start_date = $reservations[$i]->start_date->format('Y-m-d H:i:s');
				$end_date = $reservations[$i]->end_date->format('Y-m-d H:i:s');
				$additionToBaseQuery = "((((KR.start_date >= '$start_date' AND KR.end_date <= '$end_date') OR
				KR.start_date BETWEEN '$start_date' AND '$end_date' OR KR.end_date
				BETWEEN '$start_date' AND '$end_date' OR '$start_date'
				BETWEEN KR.start_date AND KR.end_date OR '$end_date' BETWEEN KR.start_date AND KR.end_date))) ";
				if($i < $length-1)
					$additionToBaseQuery .= ' OR ';
				$baseQuery .= $additionToBaseQuery;
			}
			$baseQuery .= ") as tmp WHERE (tmp.station_id = $station_id OR tmp.Tools_id IN ($tools_ids_imploded)) AND tmp.is_deleted != 1 ";
		}
		else
		{
			$baseQuery = "SELECT DISTINCT tmp.start_date, tmp.end_date FROM (
					SELECT DISTINCT KR.is_deleted, KR.station_id, KR.start_date, KR.end_date FROM KeeperReservations as KR WHERE ";
			for ($i = 0; $i < $length; $i++)
			{
				$start_date = $reservations[$i]->start_date->format('Y-m-d H:i:s');
				$end_date = $reservations[$i]->end_date->format('Y-m-d H:i:s');
				$additionToBaseQuery = "((((KR.start_date >= '$start_date' AND KR.end_date <= '$end_date')
				OR KR.start_date BETWEEN '$start_date' AND '$end_date' OR KR.end_date BETWEEN '$start_date' AND '$end_date'
				OR '$start_date' BETWEEN KR.start_date AND KR.end_date OR '$end_date' BETWEEN KR.start_date AND KR.end_date))) " ;
				if($i < $length-1)
					$additionToBaseQuery .= ' OR ';
				$baseQuery .= $additionToBaseQuery;
			}
			$baseQuery .= ") as tmp WHERE tmp.station_id = $station_id AND tmp.is_deleted != 1";
		}
		return $baseQuery;
	}

	private function calculateRecuringDates($repeatType, DateTime $startDate, DateTime $endDate, DateTime $repeatEndDate, array $repeatDays)
	{
		switch ($repeatType)
		{
			case "Daily":
				$interval = date_diff($startDate, $repeatEndDate);
				$daysCount = $interval->days+1;
				$startEndDates = array();
				for ($i = 0; $i < $daysCount; $i++)
				{
					$startEndDate = new stdClass();
					$startEndDate->start_date = clone $startDate;
					$startEndDate->start_date->add(new DateInterval('P'.$i.'D'));
					$startEndDate->end_date = clone $endDate;
					$startEndDate->end_date->add(new DateInterval('P'.$i.'D'));
					array_push($startEndDates, $startEndDate);
				}
				return $startEndDates;
				break;

			case "Weekly":
				if(!isset($repeatDays))
					return;
				$startWeekDay = date('w', strtotime($startDate->format('d-m-Y H:i:s')));
				$startEndDates = array();
				$daysDifferences = array();
				foreach ($repeatDays as $weekDay)
				{
					$daysDifference = $startWeekDay - $weekDay;
					if($daysDifference <= 0)
					{
						$daysDifferences[] = -$daysDifference;
					}
					else
					{
						$daysDifferences[] = 7 - $daysDifference;
					}
				}
				$inRange = true;
				$counter = 0;
				do{
					foreach ($daysDifferences as $daysDifference)
					{
						$dayInterval = $daysDifference+($counter*7);
						$startEndDate = new stdClass();
						$startEndDate->start_date = clone $startDate;
						$startEndDate->start_date->add(new DateInterval('P'.$dayInterval.'D'));
						$startEndDate->end_date = clone $endDate;
						$startEndDate->end_date->add(new DateInterval('P'.$dayInterval.'D'));
						if($startEndDate->start_date > $repeatEndDate )
						{
							$inRange = false;
						}
						else
							$startEndDates[] = $startEndDate;
					}
					$counter += 1;
				}while($inRange);
				return $startEndDates;
				break;

			case "Monthly":
				if(!isset($repeatDays))
					return;
				$monthDayType;
				foreach ($repeatDays as $monthDay)
					$monthDayType = $monthDay;
				$startEndDates = array();
				if($monthDayType === 'dom')
				{
					$dayOfMonth = date('j', strtotime($startDate->format('d-m-Y H:i:s'))); // get day of Month
					$inRange = true;
					$counter = 0;
					do {
						$startEndDate = new stdClass();
						$startEndDate->start_date = clone $startDate;
						$startEndDate->end_date = clone $endDate;
						date_add($startEndDate->start_date, new DateInterval('P'.$counter.'M')); // add $counter months to currentMonth
						date_add($startEndDate->end_date, new DateInterval('P'.$counter.'M')); // add $counter months to currentMonth
						$currentDay = date('j', strtotime($startEndDate->start_date->format('d-m-Y H:i:s'))); // get actual day of month
						if($currentDay != $dayOfMonth) // if current DOM is differen from start DOM, means we have come across month when there is no day like this f.e. february -> 28 (29 )days or month with 30 days, when we have 31'st
						{
							$counter += 1; // ommit one month
							$startEndDate->start_date = clone $startDate;
							$startEndDate->end_date = clone $endDate;
							date_add($startEndDate->start_date, new DateInterval('P'.$counter.'M')); // add $counter months to $currentMonth (overjumping lesser month)
							date_add($startEndDate->end_date, new DateInterval('P'.$counter.'M'));
						}
						if($startEndDate->start_date > $repeatEndDate )
						{
							$inRange = false;
						}
						else
							$startEndDates[] = $startEndDate;
						$counter += 1;
					} while($inRange);

				}
				else if($monthDayType === 'dow')
				{
					$dayOfMonth = date('j', strtotime($startDate->format('d-m-Y H:i:s')));
					$weekOfMonth = ceil(($dayOfMonth)/7);
					$dayOfWeek = date('l', strtotime($startDate->format('d-m-Y H:i:s')));
					$dayOfWeekDigit = date('w', strtotime($startDate->format('d-m-Y H:i:s')));
					$weeksOfMonth = array(
							'1' => 'first',
							'2' => 'second',
							'3' => 'third',
							'4' => 'fourth',
							'5' => 'fifth'
					);

					$inRange = true;
					$counter = 1;
					$startEndDate = new stdClass();
					$startEndDate->start_date = clone $startDate;
					$startEndDate->end_date = clone $endDate;
					$startEndDates[] = $startEndDate;
					do {
						$weekOfMonth_tmp = $weekOfMonth;
						$startEndDate = new stdClass();
						$startEndDate->start_date = clone $startDate;
						$startEndDate->end_date = clone $endDate;
						date_add($startEndDate->start_date, new DateInterval('P'.$counter.'M')); // add $counter months to currentMonth
						date_add($startEndDate->end_date, new DateInterval('P'.$counter.'M')); // add $counter months to currentMonth
						$actualMonth = date('m', strtotime($startEndDate->start_date->format('d-m-Y H:i:s')));
						$actualYear = date('Y', strtotime($startEndDate->start_date->format('d-m-Y H:i:s')));
						$weeksWithDay = $this->total_specific_days(
								$dayOfWeekDigit,
								$actualMonth,
								$actualYear);
						if($weekOfMonth_tmp > $weeksWithDay)
							$weekOfMonth_tmp = $weeksWithDay;
						else
							$weekOfMonth_tmp = $weekOfMonth;

						$startEndDate->start_date = date('m-d-Y H:i:s',strtotime($actualMonth.'/01/'.
								$actualYear. ' ' . $weeksOfMonth[$weekOfMonth_tmp] . ' '. strtolower($dayOfWeek)));
						$startEndDate->end_date = $startEndDate->start_date;
						$startEndDate->start_date = $this->changeDateString($startEndDate->start_date, null, $startDate->format('H:i:s'));
						$startEndDate->end_date = $this->changeDateString($startEndDate->end_date, null, $endDate->format('H:i:s'));
						$startEndDate->start_date = new DateTime($startEndDate->start_date);
						$startEndDate->end_date = new DateTime($startEndDate->end_date);
						if($startEndDate->start_date > $repeatEndDate )
						{
							$inRange = false;
						}
						else
							$startEndDates[] = $startEndDate;
						$counter += 1;
					} while($inRange);
				}
				return $startEndDates;
				break;
			case "Yearly":
				$interval = date_diff($startDate, $repeatEndDate);
				$yearsCount = $interval->y+1;
				$startEndDates = array();
				for ($i = 0; $i < $yearsCount; $i++)
				{
					$startEndDate = new stdClass();
					$startEndDate->start_date = clone $startDate;
					$startEndDate->start_date->add(new DateInterval('P'.$i.'Y'));
					$startEndDate->end_date = clone $endDate;
					$startEndDate->end_date->add(new DateInterval('P'.$i.'Y'));
					$startEndDates[] = $startEndDate;
				}
				return $startEndDates;
				break;
			default:
				;
				break;
		}
	}
	function week_number( $date = 'today' )
	{
		return ceil( date( 'j', strtotime( $date ) ) / 7 );

	}

	function total_specific_days($dayNumber,$month,$year)
	{
		$specificDays=0;
		$total_days=cal_days_in_month(CAL_GREGORIAN, $month, $year);
		for($i=1;$i<=$total_days;$i++)
			if(date('w',strtotime($year.'-'.$month.'-'.$i))==$dayNumber)
			$specificDays++;
		return $specificDays;
	}

	function changeDateString($dateString, $datePart, $timePart)
	{
		$dateArray = explode(' ', $dateString);
		$dateArray[0] = str_replace('-', '/', $dateArray[0]);
		$datePart = str_replace('-', '/', $datePart);
		$newDateString;
		if($datePart != null)
		{
			$newDateString = $datePart . ' ' . $dateArray[1];
			return $newDateString;
		}
		else if($timePart != null)
		{
			$newDateString = $dateArray[0] . ' ' . $timePart;
			return $newDateString;
		}
		else
			return $dateString;
			
	}
	function changeDatesToIntArray($DatesStringArray)
	{
		$integerArray = array();
		foreach ($DatesStringArray as $date)
		{
			$newDate = new DateTime($date['start_date']);
			$integerArray[] = (int)$newDate->format('Ymd');
		}
		return $integerArray;
	}
}